package top.healthylife.gateway.dto.processor;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.basics.utils.utils.BeanValidator;
import top.healthylife.gateway.dto.request.req.ApiReqDto;

import javax.validation.ConstraintViolation;
import javax.validation.groups.Default;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 此分组默认必须要填写一项,只要是这个处理类的，任何一个只要有一个值即通过
 *
 * @author maoxiaomeng
 */
@Slf4j
public class GroupOneMustBeFilledInProcessor implements GroupProcessor {

    @Override
    @SneakyThrows
    public boolean groupVerify(Class<?> aClass, ApiReqDto data, List<Field> fields) {
        List<Set<? extends ConstraintViolation<?>>> error = new ArrayList<>();
        //遍历每一个字段对象，进行属性校验
        for (Field e : fields) {
            e.setAccessible(true);
            Set<? extends ConstraintViolation<?>> constraintViolations = BeanValidator.getValidator().validateValue(aClass, e.getName(), e.get(data), Default.class);
            //如果有问题，则添加起来
            if (constraintViolations.size() > 0) {
                error.add(constraintViolations);
            }
        }
        //过滤出长度大余0的
        //如果提示错误的个数与字段个数一致，表示都有问题，直接进行异常抛出
        if (error.size() == fields.size()) {
            String errorMsg = error.stream()
                    .flatMap(Set::stream)
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.joining("-"));
            log.error("请求参数不完整,{},class:{}", error, aClass);
            throw new BusinessException("请求参数不完整,请求参数必须填写一项:" + errorMsg);
        }
        return true;
    }

}
